<template lang="html">
  <div class="content-container bookMgr-container">
    <!--筛选条件项-->
    <div class="content-condition filter searchBox" id="filterId">
      <div class="filterBtn">
        <el-button type='primary' @click="searchFun" :icon="Search">搜索</el-button>
        <el-button type="danger" @click="resetSearchData" :icon="RefreshRight">重置</el-button>
      </div>

      <el-input v-model="searchData.title" :clearable="true" placeholder="书名" style="width: 180px"> </el-input>
      <el-input v-model="searchData.author" :clearable="true" placeholder="作者" style="width: 180px"> </el-input>

      <el-select v-model="searchData.sourceType" style="width: 120px" placeholder="书源类型" clearable>
        <el-option v-for="item in options.bookSourceTypeSelector" :key="item.value" :label="item.label"
          :value="item.value"></el-option>
      </el-select>
    </div>

    <el-row class="special content-condition buttonBox" id="buttonId">
      <el-col :span="24" ref="limitBtnWidth">
        <el-space :size="10" id="actualBtnWidth" class="actualBtnWidth">
          <el-button type="primary" @click="addFun" :icon="Plus">新增</el-button>
          <el-button type="success" @click="editFun" :icon="Edit">编辑</el-button>
          <el-button type="danger" @click="deleteFun" :icon="Delete">删除</el-button>
        </el-space>
      </el-col>
    </el-row>

    <!--表格-->
    <div class="table content-condition">
      <common-table :isShowLoading="tableData.poolIsShowLoading" :tableId="tableData.tableId"
        :columns="tableData.columns" emptyText="没有找到数据" :data="tableData.datas" :tableType="tableData.tableType"
        :pager="tableData.pager" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"
        @handleSelectionChange="handleSelectionChange" @handleExpandChange="handleExpandChange" :rowkey="'id'"
        :expandRowKeys="tableData.expandRowKeys" ref="table">
        <template v-slot:table_checkbox>
          <el-table-column type="selection" align="center" width="55" fixed="left"></el-table-column>
        </template>
        <template #bookSlot="slotData">
          <el-row class="bookMgr-book-info">
            <el-col :span="8" class="bookMgr-book-img-box">
              <el-image :src="slotData.scope.row.coverPicture" class="book-img" :lazy="true" />
            </el-col>
            <el-col :span="16" class="bookMgr-book-base-info">
              <div class="title" @click="openChapter(slotData.scope.row)">{{ slotData.scope.row.title }}</div>
              <div class="author">{{ slotData.scope.row.author }}</div>
            </el-col>
          </el-row>
        </template>
        <template #descSlot="slotData">
          <div class="bookMgr-book-desc">{{ slotData.scope.row.description }}</div>
        </template>
        <template #operationSlot="slotData">
          <Button :book="slotData.scope.row"></Button>
        </template>
      </common-table>
    </div>
  </div>
  <Detail ref="bookDetailDialog"></Detail>
</template>
<script setup lang="js">
import { onMounted, ref, inject, provide } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Delete, Plus, Search, RefreshRight } from '@element-plus/icons-vue';
import { getBookPageList, deleteBook } from '@/api/bookMgr';
import _ from 'lodash';

import Detail from './components/Detail.vue';
import Button from './components/Button.vue';

const { getMultiSelectOptions, selectNames } = inject('selectCollection');
const { createTask, taskCodes } = inject('taskProvide');

const initSearchData = () => {
  return {
    title: '',
    author: '',
    sourceType: null,
    pageIndex: 0,
    pageSize: 10,
  };
};
const bookDetailDialog = ref(null);
const searchData = ref(initSearchData());

const options = ref({
  bookSourceTypeSelector: [],
});

const tableData = ref({
  tableId: 'bookTable',
  tableType: ["table"], //table-表格 dualCard-双卡片 其它-单卡片
  columns: [
    {
      slotName: "bookSlot",
      label: "书籍信息",
      width: "250",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "category",
      label: "分类",
      width: "85",
      align: "left",
      sortable: false,
      formatter: function (row) {
        return row.category + '<br/>' + row.subCategory;
      },
      show: true
    },
    {
      prop: "sourceType",
      label: "书籍来源",
      width: "90",
      align: "left",
      sortable: false,
      formatter: function (row) {
        return row.sourceTypeDesc;
      },
      show: true
    },
    {
      slotName: "descSlot",
      label: "描述",
      width: "400",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "completed",
      label: "状态",
      width: "60",
      align: "left",
      sortable: false,
      formatter: function (row) {
        return row.completed ? '完本' : '连载';
      },
      show: true
    },
    {
      prop: "isMatchSource",
      label: "匹配源",
      width: "80",
      align: "left",
      sortable: false,
      formatter: function (row) {
        return row.isMatchSourceDesc;
      },
      show: true
    },
    {
      prop: "syncChapterDate",
      label: "同步章节时间",
      width: "180",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "createUserName",
      label: "创建人",
      width: "90",
      align: "left",
      sortable: false,
      show: false
    },
    {
      prop: "createDateTime",
      label: "创建时间",
      width: "180",
      align: "left",
      sortable: false,
      show: false
    },
    {
      prop: "updateUserName",
      label: "更新人",
      width: "90",
      align: "left",
      sortable: false,
      show: false
    },
    {
      prop: "updateDateTime",
      label: "更新时间",
      width: "180",
      align: "left",
      sortable: false,
      show: false
    },
    {
      slotName: "operationSlot",
      label: "操作",
      width: "400",
      align: "left",
      sortable: false,
      show: true,
      fixed: 'right'
    },
  ],
  datas: [],
  pager: {
    //分页栏信息
    pageNo: 1, //第几页
    limit: 10, //每页记录数
    sizes: [10, 20, 50],
    total: 0, //总记录数
    isShow: true //是否显示
  },
  expandRowKeys: [],
  selectedRows: [],
  poolIsShowLoading: false,
});

// Methods
/**
 * 搜索
 */
function searchFun() {
  // 这里可以添加搜索逻辑
  console.log('搜索条件:', searchData.value);
  tableData.value.poolIsShowLoading = true;
  getDataFun();
}

/**
 * 重置
 */
function resetSearchData() {
  Object.assign(searchData.value, initSearchData());
  searchFun();
}

/**
 * 获取数据
 */
const getDataFun = _.debounce(() => {
  let params = Object.assign({}, searchData.value);
  getBookPageList(params).then((res) => {
    tableData.value.datas = res.data.data;
    tableData.value.pager = {
      total: res.data.records,
      limit: res.data.pageSize,
      pageNo: res.data.pageIndex + 1
    };
  }).finally(() => {
    tableData.value.poolIsShowLoading = false;
  });
}, 300);

/**
 * 改变页码
 * @param pageNo 当前页码
 */
function handleCurrentChange(pageNo) {
  searchData.value.pageIndex = pageNo;
  searchFun();
}

/**
 * 改变每页记录数
 * @param pageSize 每页记录数
 */
function handleSizeChange(pageSize) {
  searchData.value.pageSize = pageSize;
  searchFun();
}

/**
 * 处理选中行变化
 * @param selection 选中行数据
 */
function handleSelectionChange(selection) {
  tableData.value.selectedRows = selection;
}

function addFun() {
  bookDetailDialog.value.openDialog();
}

function editFun() {
  if (tableData.value.selectedRows.length !== 1) {
    ElMessage.warning("请选择一条记录进行编辑");
    return;
  }
  bookDetailDialog.value.openDialog(tableData.value.selectedRows[0]);
}

function deleteFun() {
  if (tableData.value.selectedRows.length === 0) {
    ElMessage.warning("请选择任意一条记录进行删除");
    return;
  }

  const bookIds = tableData.value.selectedRows.map(item => item.id);
  ElMessageBox.confirm('此操作将永久删除选中的书籍, 是否继续?',
    '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableData.value.poolIsShowLoading = true;
    deleteBook(bookIds.join(',')).then((res) => {
      if (res == null || !res.isSuccess) {
        ElMessage.error(res.message || "操作失败");
        return;
      }
      ElMessage.success("删除成功");
      searchFun();
    }).finally(() => {
      tableData.value.poolIsShowLoading = false;
    });
  }).catch(() => {
    ElMessage.info("已取消删除操作");
  });
}

/**
 * 打开目录
 * @param book 书籍
 */
function openChapter(book) {
  window.open(book.spiderUrl, '_blank');
}

/**
 * 匹配书源
 * @param book
 */
function matchBookSource(book) {
  return createTask({
    taskCode: taskCodes.matchBookSource,
    parameters: {
      filter: {
        bookId: book.id,
        bookName: book.title,
        author: book.author,
      }
    },
  });
}

/**
 * 爬取章节
 * @param book 书籍
 */
function syncBookChapter(book) {
  return createTask({
    taskCode: taskCodes.spiderChapters,
    parameters: {
      filter: {
        bookId: book.id,
        spiderUrl: book.spiderUrl,
        bookSourceType: book.sourceType,
      }
    },
  });
}


/**
 * 初始化选项数据
 */
function initOptions() {
  const keys = [selectNames.bookSourceTypeEnum];
  getMultiSelectOptions(...keys).then((res) => {
    options.value.bookSourceTypeSelector = res.getOptions(selectNames.bookSourceTypeEnum);
  });
}

onMounted(() => {
  initOptions();
});

provide('bookMgrProvide', {
  onSuccess: searchFun,
  matchBookSource: matchBookSource,
  syncBookChapter: syncBookChapter
})

// 表格方法注入
provide('tableProvide', {
  handleCurrentChange,
  handleSelectionChange,
  handleSizeChange,
});
</script>
<style lang="less">
.bookMgr-container {
  .bookMgr-book-info {
    display: flex;
    align-items: center;

    .bookMgr-book-img-box {
      text-align: center;

      .el-image {
        width: 60px;
        height: 80px;
        border-radius: 5px;
      }
    }

    .bookMgr-book-base-info {
      .title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
        text-decoration: underline;
        cursor: pointer;
      }
    }
  }

  .bookMgr-book-desc {
    white-space: normal;
    word-break: break-all;
  }
}
</style>
